﻿"use strict";

// ----------------------------------
// Depends on:
//   jQuery
//   Microsoft.Ajax
// ----------------------------------

// ----------------------------------
// Guard.

if (typeof (Sys) == 'undefined') {
	alert('Micorsoft.Ajax has not been loaded.');
}

if (typeof (jQuery) == 'undefined') {
	alert('jQuery has not been loaded.');
}

// ----------------------------------
// Constants.


// ----------------------------------
// Global variables.

// ----------------------------------
// Global functions.

// Register the namespace for the control.
Type.registerNamespace('MyLib');

//
// Define the behavior properties.
//
MyLib.MyFileUpload = function (element) {
	MyLib.MyFileUpload.initializeBase(this, [element]);

	this.m_uploadUrl = 'Upload.axd'
	this.m_flushUrl = 'swfupload.swf';
	this.m_sessionId = null;
	this.m_imageUrl = '';
	this.m_width = 61;
	this.m_height = 22;
	this.m_acceptTypes = '*.*';
	this.m_acceptTypesDescription = 'All files(*.*)';
	this.m_maxFileCount = 0;
	this.m_enabled = true;

	this.m_placeholder = null;
	this.m_queuedCount = 0;
};

//
// Create the prototype for the behavior.
//

MyLib.MyFileUpload.prototype = {


	initialize: function () {
		MyLib.MyFileUpload.callBaseMethod(this, 'initialize');

		var fuRef = this;

		var cns = this.get_element().childNodes;
		for (var i = 0; i < cns.length; ++i) {
			if (cns[i].nodeName === 'SPAN') {
				this.m_placeholder = cns[i];
				break;
			}
		}

		var swf = new SWFUpload({
			upload_url: this.m_uploadUrl,
			flash_url: this.m_flushUrl,
			post_params: {
				'session_id': this.m_sessionId
			},
			button_placeholder: this.m_placeholder,
			button_image_url: this.m_imageUrl,
			button_width: this.m_width,
			button_height: this.m_height,
			button_disabled: !this.m_enabled,
			button_cursor: SWFUpload.CURSOR.HAND,
			file_size_limit: '20480',
			file_types: this.m_acceptTypes,
			file_types_description: this.m_acceptTypesDescription,
			file_upload_limit: this.m_maxFileCount,
			// debug: true,
			/* Events */
			file_dialog_complete_handler: function (nums, numq, numt) {
				fuRef.m_queuedCount = numt;
				if (numt === 0) {
					return;
				}

				my_showOverlay();
				fuRef._showUploadMessage();
				this.startUpload();
			},
			upload_start_handler: function (fo) {
				Sys.Debug.trace('Uploading [' + fo.id + '], "' + fo.name + '" ...');
				fuRef._setUploadMessage(fuRef._formatTitle(fo), 0);
			},
			upload_progress_handler: function (fo, bs, bt) {
				var pc = 0;
				if (bt !== 0) {
					pc = bs * 100 / bt;
				}
				fuRef._setUploadMessage(fuRef._formatTitle(fo), pc);
			},
			upload_success_handler: function (fo, rsp) {
				Sys.Debug.trace('Succeeded to upload [' + fo.id + '], "' + fo.name + '" :' + rsp);
				fuRef._setUploadMessage(fuRef._formatTitle(fo), 100);
			},
			upload_error_handler: function (fo, err, msg) {
				Sys.Debug.trace('Failed to upload [' + fo.id + '], "' + fo.name + '" :' + msg);
			},
			upload_complete_handler: function (fo) {
				if (swf.getStats().files_queued !== 0) {
					this.startUpload();
				} else {
					fuRef._hideUploadMessage();
					my_hideOverlay();
				}
			}
		});
	},

	dispose: function () {
		$clearHandlers(this.m_placeholder);

		MyLib.MyFileUpload.callBaseMethod(this, 'dispose');
	},

	_formatTitle: function (fo) {
		return '(' + (fo.index + 1) + '/' + this.m_queuedCount + ')' + fo.name;
	},

	_showUploadMessage: function () {
		var sw = document.documentElement.clientWidth || document.body.clientWidth;
		var st = document.documentElement.scrollTop || document.body.scrollTop;

		var progress = jQuery('<div class="myFileUpload_progress"></div>');
		var progTitle = jQuery('<div class="myFileUpload_progressTitle"></div>');
		var progBar = jQuery('<div class="myFileUpload_progressBar"></div>');
		var progValue = jQuery('<div class="myFileUpload_progressValue"></div>');
		var progBarCnt = jQuery('<div class="myFileUpload_progressBarCnt"></div>');
		progress.append(progTitle);
		progBarCnt.css('left', 0);
		progBarCnt.css('top', 0);
		progBarCnt.width(0);
		progBar.append(progBarCnt);
		progress.append(progBar);
		progress.append(progValue);
		jQuery(document.body).prepend(progress);

		progress.css('position', 'absolute');
		progress.css('z-index', my_updateMessageZIndex);
		var ml = progress.width();
		var mt = progress.offset().top;
		progress.offset({ left: (sw - ml) / 2, top: mt + st });
	},

	_setUploadMessage: function (fn, pc) {
		var progress = jQuery('div.myFileUpload_progress');
		var progTitle = progress.children('.myFileUpload_progressTitle');
		var progBar = progress.children('.myFileUpload_progressBar');
		var progBarCnt = progBar.children('.myFileUpload_progressBarCnt');
		var progValue = progress.children('.myFileUpload_progressValue');

		progTitle.text(fn);
		progBarCnt.width(pc + '%');
		progValue.text(pc.toFixed(1) + '%');
	},

	_hideUploadMessage: function () {
		var progress = jQuery('div.myFileUpload_progress');
		progress.hide(0, function () {
			progress.remove().empty();
		});
	},

	//
	// Event delegates
	//


	//
	// Control properties
	//

	get_uploadUrl: function () {
		return this.m_uploadUrl;
	},

	set_uploadUrl: function (value) {
		if (this.m_uploadUrl !== value) {
			this.m_uploadUrl = value;
			this.raisePropertyChanged('uploadUrl');
		}
	},

	get_flashUrl: function () {
		return this.m_flushUrl;
	},

	set_flashUrl: function (value) {
		if (this.m_flushUrl !== value) {
			this.m_flushUrl = value;
			this.raisePropertyChanged('flashUrl');
		}
	},

	get_sessionId: function () {
		return this.m_sessionId;
	},

	set_sessionId: function (value) {
		if (this.m_sessionId !== value) {
			this.m_sessionId = value;
			this.raisePropertyChanged('sessionId');
		}
	},

	get_imageUrl: function () {
		return this.m_imageUrl;
	},

	set_imageUrl: function (value) {
		if (this.m_imageUrl !== value) {
			this.m_imageUrl = value;
			this.raisePropertyChanged('imageUrl');
		}
	},

	get_width: function () {
		return this.m_width;
	},

	set_width: function (value) {
		if (this.m_width !== value) {
			this.m_width = value;
			this.raisePropertyChanged('width');
		}
	},

	get_height: function () {
		return this.m_height;
	},

	set_height: function (value) {
		if (this.m_height !== value) {
			this.m_height = value;
			this.raisePropertyChanged('height');
		}
	},

	get_acceptTypes: function () {
		return this.m_acceptTypes;
	},

	set_acceptTypes: function (value) {
		if (this.m_acceptTypes !== value) {
			this.m_acceptTypes = value;
			this.raisePropertyChanged('acceptTypes');
		}
	},

	get_acceptTypesDescription: function () {
		return this.m_acceptTypesDescription;
	},

	set_acceptTypesDescription: function (value) {
		if (this.m_acceptTypesDescription !== value) {
			this.m_acceptTypesDescription = value;
			this.raisePropertyChanged('acceptTypesDescription');
		}
	},

	get_maxFileCount: function () {
		return this.m_maxFileCount;
	},

	set_maxFileCount: function (value) {
		if (this.m_maxFileCount !== value) {
			this.m_maxFileCount = value;
			this.raisePropertyChanged('maxFileCount');
		}
	},

	get_enabled: function () {
		return this.m_enabled;
	},

	set_enabled: function (value) {
		if (this.m_enabled !== value) {
			this.m_enabled = value;
			this.raisePropertyChanged('enabled');
		}
	}
}

// Optional descriptor for JSON serialization.
MyLib.MyFileUpload.descriptor = {
	properties: [
		{ name: 'uploadUrl', type: String },
		{ name: 'flashUrl', type: String },
		{ name: 'sessionId', type: String },
		{ name: 'imageUrl', type: String },
		{ name: 'width', type: Number },
		{ name: 'height', type: Number },
		{ name: 'acceptTypes', type: String },
		{ name: 'acceptTypesDescription', type: String },
		{ name: 'maxFileCount', type: Number },
		{ name: 'enabled', type: Boolean }
	]
};

// Register the class as a type that inherits from Sys.UI.Control.
MyLib.MyFileUpload.registerClass('MyLib.MyFileUpload', Sys.UI.Control);

Sys.Application.notifyScriptLoaded();
